#include "uart_tool.h"

int myserialOpen (const char *device, const int baud)
{
  struct termios options ;
  speed_t myBaud ;
  int     status, fd ;

  switch (baud)
  {
    case    9600:	myBaud =    B9600 ; break ;
    case  115200:	myBaud =  B115200 ; break ;
    default:
      return -2 ;
  }

  if ((fd = open (device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK)) == -1)
    return -1 ;

  fcntl (fd, F_SETFL, O_RDWR) ;

// Get and modify current options:

  tcgetattr (fd, &options) ;

    cfmakeraw   (&options) ;
    cfsetispeed (&options, myBaud) ;
    cfsetospeed (&options, myBaud) ;

    options.c_cflag |= (CLOCAL | CREAD) ;
    options.c_cflag &= ~PARENB ;
    options.c_cflag &= ~CSTOPB ;
    options.c_cflag &= ~CSIZE ;
    options.c_cflag |= CS8 ;
    options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG) ;
    options.c_oflag &= ~OPOST ;

    options.c_cc [VMIN]  =   0 ;
    options.c_cc [VTIME] = 100 ;	// Ten seconds (100 deciseconds)

  tcsetattr (fd, TCSANOW, &options) ;

  ioctl (fd, TIOCMGET, &status);

  status |= TIOCM_DTR ;
  status |= TIOCM_RTS ;

  ioctl (fd, TIOCMSET, &status);

  usleep (10000) ;	// 10mS

  return fd ;
}

// 会传递0XAA 0X55 0X46 0x00 0X55 0XAA类似的参数
void serial_sendString(int fd,const unsigned char *s,int len)
{   
    int ret;

    ret = write(fd,s,len);
    printf("%s|%s|%d\n",__FILE__,__func__,__LINE__);
    if(ret < 0)
    {
        printf("send error!\n");
    }
}

void serial_getString(int fd,unsigned char *s)
{
    int n_read;

    n_read = read(fd,s,32);
    
    if(n_read < 0)
    { 
      printf("%s|%s|%d\n",__FILE__,__func__,__LINE__);
      perror("read");
      printf("rev error!\n");
    }
}

int myserialGetchar (const int fd)
{
  char x ;

  if (read (fd, &x, 1) != 1)
    return -1 ;

  return ((int)x) & 0xFF ;
}
